//
// Created by TheHun on 2020/10/20.
//
#include "..\\code\\dataStruct.h"
#include "..\\code\\common.h"
#include <math.h>
#include <stdio.h>

int linearDistanceRelay(Phasor Z, Phasor Zset, double angleSet1, double angleSet2);
/**
 * 四边形阻抗继电器-110kV
 * @param Um 测量电压
 * @param Im 测量电流
 * @param ampZzd 定值幅值
 * @param angleZzd 定值相角
 * @param ampZrec 长定值幅值
 * @return 判别结果
 */
int quadrilateralDistanceRelay(Phasor Um, Phasor Im, double ampZzd, double angleZzd, double ampZrec) {
    int line[4];

    Phasor Z = phasorDiv(Um, Im);
    Phasor Zzd = ampAngle2phasor(ampZzd, angleZzd);
    Phasor Zrec = ampAngle2phasor(ampZrec, angleZzd);
    Phasor halfZzd = phasorNumMulti(0.5, Zzd);
    Phasor Rset;
    double rad = angleZzd / 180 * PI;
    Rset.real = ampZzd / (2.0 * sin(rad)); Rset.img = 0.0;
    Phasor zero;
    zero.real = zero.img = 0.0;

    line[0] = linearDistanceRelay(Z, halfZzd, angleZzd - 90, angleZzd + 90); // AB
    line[1] = linearDistanceRelay(Z, Rset, angleZzd, angleZzd + 180); // BC
    line[2] = linearDistanceRelay(Z, Zrec, angleZzd + 90, angleZzd + 270); // CD
    line[3] = linearDistanceRelay(Z, zero, -75, 105); // DA

    return (line[0] && line[1] && line[2] && line[3]);
}

/**
 * 直线特性的阻抗继电器
 * @param Z 测量阻抗
 * @param Zset 整定阻抗
 * angleSet1 < angleSet2
 * @param angleSet1 相角定值1
 * @param angleSet2 相角定值2
 * @return 判别结果
 */
int linearDistanceRelay(Phasor Z, Phasor Zset, double angleSet1, double angleSet2) {
    double angleDiff = phasorAngle(phasorSub(Z, Zset));
    if (angleSet2 <= 0.0001) {
        angleSet1 += 360;
        angleSet2 += 360;
    } else if (angleSet1 < 0.0001) {
        angleSet1 += 360;
        if ((angleDiff >= angleSet1 && angleDiff <= 360.0) || (angleDiff <= angleSet2 && angleDiff >= 0.0)) {
            return 1;
        } else {
            return 0;
        }
    }

    if (angleDiff >= angleSet1 && angleDiff <= angleSet2) {
        return 1;
    } else {
        return 0;
    }
}